<?php


namespace app\admin\controller;


use think\Controller;
use think\Db;
use think\Request;

class News extends Controller
{
    public function index()
    {
        return $this->fetch();
    }

    public function queryNews()
    {
        if($this->request->isAjax()){
            $data = Db::table('hisi_cms_article')
                ->where('status',5)
                ->page(1)
                ->limit(15)
                ->select();
            return json(["code" => 0,"data"=>$data]);
        }
    }

    public function add()
    {
        return $this->fetch();
    }

    public function addNews(Request $request)
    {
        //接收
        $data = $request->post();
        $articleData = [
            "author" => $data["author"],
            "title" => $data["title"],
            "avatar" => $data["avatar"],
            "content" => $data["content"],
            "detail" => $data["detail"],
            "imgSrc" => $data["imgSrc"],
            "headImgSrc" => $data["headImgSrc"],
            'dateTime' => time()
        ];
        $result = Db::table('hisi_cms_article')->insert($articleData);

        if ($result === 1) {
            $this->success("增加成功",url("admin/news/index"),"",1);
        } else {
            $this->error("增加失败",url("admin/news/add"),"",1);
        }
    }

    public function delete_news(Request $request)
    {
        $id = $request->param('id');
        $result = Db::table('hisi_cms_article')->where('id',$id)->delete();
        if ($result === 1){
            return json(['code'=>1,'msg'=>"删除成功"]);
        }
    }

    public function edit(Request $request)
    {
        $id = $request->param('id');

        $data = Db::table('hisi_cms_article')->where('id',$id)->find();

        $this->assign("data",$data);
        return $this->fetch();
    }

    public function saveNews(Request $request)
    {

        $data = $request->post();
        /*$dataDetail = preg_replace('/\s+/', '', $data['detail']);*/
        $articleData = [
            "author" => $data["author"],
            "title" => $data["title"],
            "avatar" => $data["avatar"],
            "content" => $data["content"],
            "detail" => $data['detail'],
            "imgSrc" => $data["imgSrc"],
            "headImgSrc" => $data["headImgSrc"],
        ];
        $result = Db::table("hisi_cms_article")->where('id',$data['id'])->update($articleData);
        if ($result === 1) {
            $this->success("修改成功",url("admin/news/index"),"",1);
        } else {
            $this->error("修改失败",url("admin/news/index"),"",1);
        }
    }
}